﻿#include "change_info.h"
#include "ui_change_info.h"
#include"global.h"
#include"email.h"
Change_info::Change_info(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Change_info)
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:\\LIBDB\\data.db");
    ui->setupUi(this);
    ui->confirm->setText("确认");
    user =global::user;
    QSqlQuery query(db);
    if(!db.open()){
        qDebug()<<"fail to open ";
    }else{
        QString q="SELECT * FROM Reader where ID = '"+user+"'";
        query.exec(q);
        while(query.next()){
            ui->major->setPlaceholderText(query.value("major").toString());
            ui->phone->setPlaceholderText(query.value("phone").toString());
            ui->email->setPlaceholderText(query.value("email").toString());
            ui->age->setPlaceholderText(query.value("age").toString());
        }
    }
    db.close();
}

Change_info::~Change_info()
{
    qDebug()<<"~ work";
    emit buttonenabled();
    delete ui;
}

void Change_info::on_confirm_clicked()
{
    bool flag =false;
    bool check = true;
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:\\LIBDB\\data.db");
    db.open();
    QString pws = ui->password->text();
    QString phone = ui->phone->text();
    QString age = ui->age->text();
    QString major = ui->major->text();
    QString mail = ui->email->text();
    Email *tmp =new Email(mail);
    if(major!=""){
        QSqlQuery query(db);
        QString command = "UPDATE Reader SET major = '"+major+"'where ID ='"+user+"'";
        query.exec(command);
        flag = true;
    }
    if(pws != ""){
        QSqlQuery query(db);
        QString command = "UPDATE Reader SET password = '"+pws+"'where ID ='"+user+"'";
        query.exec(command);
        flag = true;
    }
    if(phone != ""){
        QSqlQuery query(db);
        QString command = "UPDATE Reader SET phone = '"+phone+"'where ID ='"+user+"'";
        query.exec(command);
        flag = true;
    }
    if(age != ""){
        QSqlQuery query(db);
        QString command = "UPDATE Reader SET age = '"+age+"'where ID ='"+user+"'";
        query.exec(command);
        flag = true;
    }
    if(mail!=""){
        if(tmp->check_email()){
            QSqlQuery query(db);
            QString command = "UPDATE Reader SET email = '"+mail+"'where ID ='"+user+"'";
            query.exec(command);
//            emit mailChange();
            flag = true;
        }else{
            QMessageBox::warning(this,"提示","邮箱有误!");
            check = false;
        }
    }
    delete tmp;

    if(flag&&check){
        QMessageBox::information(this,"提示","修改成功！");
        this->close();
    }else if(!flag&&check){
        QMessageBox::information(this,"提示","尚未修改！");
    }
}

